
import { getMenu } from '@/api/index'
const modules = import.meta.glob(['./views/pages/**/*.vue', './views/pages_plugs/**/*.vue'])

// **  任意目录
// * 任意文件
import type { Router } from 'vue-router'
import { useUserStore } from "@/stores/user";

// console.log(modules)

type callBack = () => void
export default function (router: Router, cb: callBack) {
  const menus = sessionStorage.getItem('menus') || ''
  const menulist = sessionStorage.getItem('menulist') || ''
  const userInfoString = sessionStorage.getItem('userInfo') || ''

  // console.log(userInfoString)

  const { setUserInfo, setMenu } = useUserStore()

  // console.log(menulist)

  if (menulist && userInfoString) {
    // 有的话 动态添加
    addRoute(JSON.parse(menulist))
    setMenu(JSON.parse(menus))

    if (userInfoString) {
      setUserInfo(JSON.parse(userInfoString))
    }


    if (typeof cb === 'function') {
      cb()
    }

  } else {



    getMenu().then((res: any) => {


      console.log(res);

      if (res.data.code === 0) {

        sessionStorage.setItem('menus', JSON.stringify(res.data.menus))
        sessionStorage.setItem('menulist', JSON.stringify(res.data.menuList))
        sessionStorage.setItem('userInfo', JSON.stringify(res.data.userInfo))
        setUserInfo(res.data.userInfo)
        setMenu(res.data.menus)
        addRoute(res.data.menuList)
      }

      if (typeof cb === 'function') {
        cb()
      }

    }).catch((err: any) => {


      console.log(err);


    })
  }



  function addRoute(menuList: any) {
    // console.log(menuList)
    menuList.forEach((item: any) => {

      const component = modules['./views' + item.url + '.vue']
      console.log(component);

      if (component !== undefined) {
        router.addRoute('home', {
          path: item.url,
          name: item.menu_id,
          component: component
        })


      }


    });

  }
}

